package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.Result;
import com.heima.context.ResidentContext;
import com.heima.domain.dto.PageDTO;
import com.heima.domain.po.DrugOrder;
import com.heima.domain.po.Drugs;
import com.heima.domain.query.DrugOrderQuery;
import com.heima.mapper.DrugOrderMapper;
import com.heima.service.IDrugOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 药物订单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-04
 */
@Service
public class DrugOrderServiceImpl extends ServiceImpl<DrugOrderMapper, DrugOrder> implements IDrugOrderService {
   public Result findByPage(DrugOrderQuery drugOrderQuery){
       if(ResidentContext.getCurrentId() == null) return Result.error("请先登录");
       Long userId = ResidentContext.getCurrentId();
        String name = drugOrderQuery.getName();
        Integer status = drugOrderQuery.getStatus();
       LocalDateTime  beginTime = drugOrderQuery.getBeginTime();
         LocalDateTime endTime = drugOrderQuery.getEndTime();
         Integer pageNum= drugOrderQuery.getPageNum();
            Integer pageSize = drugOrderQuery.getPageSize();
       Page<DrugOrder> p = this.lambdaQuery()
               .eq(DrugOrder::getUserId, userId) // 查询当前用户的订单
               .like(StringUtils.isNotBlank(name), DrugOrder::getName, name)
               .eq(status != null, DrugOrder::getStatus, status)
               .ge(beginTime != null, DrugOrder::getCreateTime, beginTime)
               .le(endTime != null, DrugOrder::getCreateTime, endTime)
                .orderByDesc(DrugOrder::getCreateTime)
               .page(new Page<>(pageNum, pageSize));
       List<DrugOrder> records = p.getRecords();
       if (records.isEmpty()) { // 如果结果为空
           return Result
                   .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageNum, new ArrayList<>())); // 返回空数据的分页结果
       }
       return Result
               .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageSize, records)); // 返回查询到的数据分页结果
   }

   }

